package com.home.fansea.config;

import com.home.fansea.listener.RedisMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.stream.Consumer;
import org.springframework.data.redis.connection.stream.ReadOffset;
import org.springframework.data.redis.connection.stream.StreamOffset;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.stream.StreamMessageListenerContainer;
import org.springframework.data.redis.stream.Subscription;

import java.time.Duration;
 
/**
 * @Description: TODO
 **/
@Configuration
public class RedisMQConfig {
 
    @Autowired
    private RedisMQListener redisMQListener;
 
    /*@Autowired
    private RedisUtils redisUtils;*/

    /*@Autowired
    private static RedisTemplate<Object, Object> redisTemplate;*/
    private RedisTemplate redisTemplate;
    private static final Logger log = LoggerFactory.getLogger(RedisMQConfig.class);
 
   @Autowired
    public RedisMQConfig(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
 
    @Bean
    public Subscription subscription(RedisConnectionFactory redisConnectionFactory) {

        StreamMessageListenerContainer.StreamMessageListenerContainerOptions options = StreamMessageListenerContainer.StreamMessageListenerContainerOptions.builder()
                .pollTimeout(Duration.ofSeconds(1)).build();
        StreamMessageListenerContainer streamMessageListenerContainer = StreamMessageListenerContainer.create(redisConnectionFactory, options);
        Subscription subscription = streamMessageListenerContainer.receiveAutoAck(Consumer.from("cs1", "c1"), StreamOffset.create("stream.mqtt", ReadOffset.lastConsumed()), redisMQListener);
        streamMessageListenerContainer.start();
        return subscription;
    }
 
}